// I2C-24C02 读写实验平台 - 前端逻辑

let waveformChart = null;
let updateInterval = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeChart();
    loadStatus();
    startAutoRefresh();
});

// 初始化波形图
function initializeChart() {
    const ctx = document.getElementById('waveformChart').getContext('2d');
    waveformChart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: 'SCL',
                data: [],
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                fill: false,
                tension: 0,
                pointRadius: 0
            }, {
                label: 'SDA',
                data: [],
                borderColor: 'rgb(54, 162, 235)',
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                fill: false,
                tension: 0,
                pointRadius: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    type: 'linear',
                    title: {
                        display: true,
                        text: '时间 (ms)'
                    }
                },
                y: {
                    min: -0.5,
                    max: 1.5,
                    ticks: {
                        stepSize: 1,
                        callback: function(value) {
                            return value === 0 ? '低' : value === 1 ? '高' : '';
                        }
                    }
                }
            },
            plugins: {
                legend: {
                    display: true
                }
            }
        }
    });
}

// 更新配置
async function updateConfig() {
    const deviceAddress = parseInt(document.getElementById('deviceAddress').value);
    const writeProtect = document.getElementById('writeProtect').value === 'true';
    
    try {
        const response = await fetch('/api/config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                device_address: deviceAddress,
                write_protected: writeProtect
            })
        });
        
        const data = await response.json();
        showMessage('配置更新成功', 'success');
    } catch (error) {
        showMessage('配置更新失败: ' + error.message, 'error');
    }
}

// 单字节写入
async function writeSingleByte() {
    const address = parseInt(document.getElementById('writeAddress').value);
    const dataStr = document.getElementById('writeData').value.trim();
    
    if (!dataStr) {
        showMessage('请输入要写入的数据', 'error');
        return;
    }
    
    const values = dataStr.split(/\s+/).map(hex => parseInt(hex, 16)).filter(v => !isNaN(v));
    
    if (values.length === 0) {
        showMessage('请输入有效的十六进制数据', 'error');
        return;
    }
    
    try {
        const response = await fetch('/api/write', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                address: address,
                values: values.slice(0, 1)  // 只取第一个字节
            })
        });
        
        const data = await response.json();
        if (data.error) {
            showMessage(data.error, 'error');
        } else {
            showMessage(`成功写入 ${data.bytes_written} 字节`, 'success');
            loadStatus();
        }
    } catch (error) {
        showMessage('写入失败: ' + error.message, 'error');
    }
}

// 页写入
async function writePage() {
    const address = parseInt(document.getElementById('writeAddress').value);
    const dataStr = document.getElementById('writeData').value.trim();
    
    if (!dataStr) {
        showMessage('请输入要写入的数据', 'error');
        return;
    }
    
    const values = dataStr.split(/\s+/).map(hex => parseInt(hex, 16)).filter(v => !isNaN(v));
    
    if (values.length === 0) {
        showMessage('请输入有效的十六进制数据', 'error');
        return;
    }
    
    // 24C02页大小为16字节
    const pageSize = 16;
    const pageStart = Math.floor(address / pageSize) * pageSize;
    const maxWrite = Math.min(values.length, pageSize - (address - pageStart));
    
    try {
        const response = await fetch('/api/write', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                address: address,
                values: values.slice(0, maxWrite)
            })
        });
        
        const data = await response.json();
        if (data.error) {
            showMessage(data.error, 'error');
        } else {
            showMessage(`页写入成功 ${data.bytes_written} 字节`, 'success');
            loadStatus();
        }
    } catch (error) {
        showMessage('页写入失败: ' + error.message, 'error');
    }
}

// 随机读取
async function readRandom() {
    const address = parseInt(document.getElementById('readAddress').value);
    const length = parseInt(document.getElementById('readLength').value);
    
    try {
        const response = await fetch('/api/read', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                address: address,
                length: length
            })
        });
        
        const data = await response.json();
        if (data.error) {
            showMessage(data.error, 'error');
        } else {
            displayData(data);
            loadStatus();
        }
    } catch (error) {
        showMessage('读取失败: ' + error.message, 'error');
    }
}

// 顺序读取
async function readSequential() {
    const address = parseInt(document.getElementById('readAddress').value);
    const length = parseInt(document.getElementById('readLength').value);
    
    try {
        const response = await fetch('/api/read', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                address: address,
                length: Math.min(length, 256 - address)  // 确保不超出范围
            })
        });
        
        const data = await response.json();
        if (data.error) {
            showMessage(data.error, 'error');
        } else {
            displayData(data);
            loadStatus();
        }
    } catch (error) {
        showMessage('顺序读取失败: ' + error.message, 'error');
    }
}

// 显示数据
function displayData(data) {
    // 十六进制显示
    document.getElementById('hexDisplay').textContent = data.hex.join(' ');
    
    // ASCII显示
    document.getElementById('asciiDisplay').textContent = data.ascii;
    
    // 十进制显示
    document.getElementById('decimalDisplay').textContent = data.data.join(', ');
}

// 加载状态
async function loadStatus() {
    try {
        const response = await fetch('/api/status');
        const data = await response.json();
        
        // 更新配置显示
        document.getElementById('deviceAddress').value = data.device_address;
        document.getElementById('writeProtect').value = data.write_protected.toString();
        
        // 更新日志
        updateLogDisplay(data.log);
        
        // 更新波形图
        updateWaveform(data.waveform);
    } catch (error) {
        console.error('加载状态失败:', error);
    }
}

// 更新日志显示
function updateLogDisplay(log) {
    const logDisplay = document.getElementById('logDisplay');
    logDisplay.innerHTML = '';
    
    log.forEach(entry => {
        const div = document.createElement('div');
        div.className = 'mb-1';
        div.innerHTML = `<span class="text-gray-500">[${entry.time.toFixed(3)}ms]</span> 
                        <span class="text-blue-600">${entry.event}</span> 
                        <span class="text-green-600">SCL:${entry.scl}</span> 
                        <span class="text-purple-600">SDA:${entry.sda}</span>`;
        logDisplay.appendChild(div);
    });
    
    // 自动滚动到底部
    logDisplay.scrollTop = logDisplay.scrollHeight;
}

// 更新波形图
function updateWaveform(waveform) {
    if (!waveformChart || waveform.length === 0) return;
    
    const sclData = waveform.map(point => ({
        x: point.time * 1000,  // 转换为毫秒
        y: point.scl
    }));
    
    const sdaData = waveform.map(point => ({
        x: point.time * 1000,
        y: point.sda
    }));
    
    waveformChart.data.datasets[0].data = sclData;
    waveformChart.data.datasets[1].data = sdaData;
    waveformChart.update('none');
}

// 清除日志
async function clearLog() {
    try {
        await fetch('/api/clear');
        loadStatus();
    } catch (error) {
        showMessage('清除日志失败: ' + error.message, 'error');
    }
}

// 显示消息
function showMessage(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} fixed top-4 right-4 z-50`;
    alertDiv.textContent = message;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}

// 自动刷新
function startAutoRefresh() {
    updateInterval = setInterval(() => {
        loadStatus();
    }, 2000);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (updateInterval) {
        clearInterval(updateInterval);
        updateInterval = null;
    }
}

// 页面卸载时停止刷新
window.addEventListener('beforeunload', stopAutoRefresh);

// 工具函数：十六进制字符串转字节数组
function hexStringToBytes(hexString) {
    return hexString.split(/\s+/).map(hex => parseInt(hex, 16)).filter(v => !isNaN(v));
}

// 工具函数：字节数组转十六进制字符串
function bytesToHexString(bytes) {
    return bytes.map(b => b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
}
